package com.yixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixun.entity.DiQu;
import com.yixun.entity.YxUser;
import com.yixun.mapper.DiQuMapper;
import com.yixun.service.DiQuService;
import com.yixun.service.LogSetService;
import com.yixun.util.LogUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DiQuServiceImpl implements DiQuService {

    @Resource
    private DiQuMapper diQuMapper;

    @Resource
    private LogSetService logSetService;

    @Override
    public String getDiquTree(Long dq_id) {
        DiQu diQu = diQuMapper.getDiQuBean(dq_id);
        if (null != diQu) {
            List<DiQu> all_list = diQuMapper.getAllDiquList();
            String json_str = "[{\"id\":\"" + dq_id + "\",\"text\":\""
                    + diQu.getDq_name() + "\",\"attributes\":{\"level\":\""+diQu.getDq_level()+"\"}";
            String child_str = getDiquTreeHandle(getChildDiquList(all_list,dq_id), all_list);
            if (child_str != null && !"".equals(child_str)) {
                json_str += ",\"children\":[" + child_str + "]";
            }
            json_str += "}]";
            return json_str;
        } else {
            return "[]";
        }
    }

    @Override
    public String getAllChildDiquTree(Long dq_id) {
        DiQu diQu = diQuMapper.getDiQuBean(dq_id);
        if (null != diQu) {
            List<DiQu> all_list = diQuMapper.getAllDiquList();
            String child_str = getAllDiquTreeHandle(getChildDiquList(all_list,dq_id), all_list);
            return "["+child_str+"]";
        } else {
            return "[]";
        }
    }

    @Override
    public List<DiQu> getChildDiquList(Long dq_id) {
        return diQuMapper.getChildDiquList(dq_id);
    }

    @Override
    public DiQu getDiquByDqId(Long dq_id) {
        return diQuMapper.getDiQuBean(dq_id);
    }

    @Override
    @Transactional
    public int insertDiQu(YxUser sessionUser, DiQu diQu) {
        int row = 0;
        String tree_position = diQuMapper.getTreePosition(diQu.getParent_id());
        diQu.setTree_position(tree_position + diQu.getDq_id() + "$");
        row = diQuMapper.insertDiQu(diQu);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.ADD, "地区", JSON.toJSONString(diQu), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public DiQu getDiquBean(Long dq_id) {
        return diQuMapper.getDiQuBean(dq_id);
    }

    @Override
    @Transactional
    public int updateDiQu(YxUser sessionUser, DiQu diQu) {
        int row = 0;
        row = diQuMapper.updateDiQu(diQu);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE, "地区", JSON.toJSONString(diQu), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int delDiQu(YxUser sessionUser, String id) {
        int row = 0;
        String[] ids = id.split(",");
        for (String dq_id: ids) {
            String treePosition = diQuMapper.getTreePosition(Long.parseLong(dq_id));
            diQuMapper.delDiQu(treePosition);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.DELETE, "地区", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int moveDiQu(YxUser sessionUser, Map map) {
        int row = 0;
        String parent_id = (String) map.get("parent_id");
        String dq_ids = (String) map.get("dq_ids");
        String parent_position = diQuMapper.getTreePosition(Long.parseLong(parent_id));
        if (null != dq_ids && dq_ids != "") {
            String[] dqIds = dq_ids.split(",");
            for (String dq_id: dqIds) {
                moveDiQuHandle(dq_id, parent_id, parent_position);
                row++;
            }
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.MOVE,"地区", JSON.toJSONString(map), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int sortDiQu(YxUser sessionUser, String id) {
        int row = 0;
        Map<String, String> map = new HashMap<>();
        String[] ids = id.split(",");
        for (int i = 0; i < ids.length; i++) {
            map.put("sort_id", (i + 1) + "");
            map.put("dq_id", ids[i]);
            diQuMapper.sortDiQu(map);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.SAVE_SORT,"地区", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }

    /*=======================================moveDiQuHandle===============================================*/

    public void moveDiQuHandle(String dq_id, String parent_id, String parent_position){
        String diqu_position = parent_position + dq_id + "$";
        Map<String, Object> map = new HashMap<>();
        map.put("dq_id",dq_id);
        map.put("parent_id", parent_id);
        map.put("tree_position", diqu_position);

        if (diQuMapper.moveDiQu(map) > 0) {
            // 该节点下的子节点一并转移
            List<DiQu> child_list = getChildDiquList(Long.parseLong(dq_id));
            if (null != child_list && child_list.size() > 0) {
                for (DiQu child: child_list) {
                    moveDiQuHandle(child.getDq_id()+"", dq_id, diqu_position);
                }
            }
        }
    }

    /*=======================================moveDiQuHandle===============================================*/

    /*============================================DiquTreeUtil============================================*/

    public String getDiquTreeHandle(List<DiQu> dl, List<DiQu> all_list){
        String json_str = "";
        if (null != dl && dl.size() > 0) {
            String child_state = "";
            for (DiQu dq: dl) {
                if (dq.getDq_level() < 4) {
                    if (dq.getDq_level() < 5) {
                        child_state = "\"state\":\"closed\",";
                    } else {
                        child_state = "";
                    }
                    json_str += ",{";
                    json_str += "\"id\":\"" + dq.getDq_id() + "\","
                            + "\"text\":\"" + dq.getDq_name()+ "\","+child_state+"\"attributes\":{\"level\":\""+dq.getDq_level()+"\"}";
                    String child_str = getDiquTreeHandle(getChildDiquList(all_list,dq.getDq_id()), all_list);
                    if (child_str != null && !"".equals(child_str)) {
                        json_str += ",\"children\":[" + child_str + "]";
                    }
                    json_str += "}";
                }
            }
            if (json_str != null && !"".equals(json_str)) {
                json_str = json_str.substring(1);
            }
        }
        return json_str;
    }

    public List<DiQu> getChildDiquList(List<DiQu> all_list,Long parent_id){
        List<DiQu> result_list = new ArrayList<>();
        for (DiQu dq: all_list) {
            if (parent_id.equals(dq.getParent_id())) {
                result_list.add(dq);
            }
        }
        return result_list;
    }

    public String getAllDiquTreeHandle(List<DiQu> dl, List<DiQu> all_list){
        String json_str = "";
        if (null != dl && dl.size() > 0) {
            for (DiQu dq: dl) {
                json_str += ",{";
                json_str += "\"id\":\"" + dq.getDq_id() + "\","
                        + "\"text\":\"" + dq.getDq_name()+ "\",\"attributes\":{\"level\":\""+dq.getDq_level()+"\"}";
                String child_str = getAllDiquTreeHandle(getChildDiquList(all_list,dq.getDq_id()), all_list);
                if (child_str != null && !"".equals(child_str)) {
                    json_str += ",\"children\":[" + child_str + "]";
                }
                json_str += "}";
            }
            if (json_str != null && !"".equals(json_str)) {
                json_str = json_str.substring(1);
            }
        }
        return json_str;
    }


    /*============================================DiquTreeUtil============================================*/
}
